/**
 * 评论相关接口
 */

import { get, post, del } from '@/utils/request'

// 评论信息
export interface CommentInfo {
    id: number
    workId: number
    userId: number
    content: string
    parentId?: number | null
    replyToUserId?: number | null
    likesCount: number
    repliesCount: number
    isDeleted: boolean
    createdAt: string
    updatedAt: string
    user: {
        id: number
        username: string
        avatar?: string
    }
    replyToUser?: {
        id: number
        username: string
        avatar?: string
    }
}

// 创建评论请求
export interface CreateCommentRequest {
    workId: number
    content: string
    parentId?: number
    replyToUserId?: number
}

// 创建评论响应
export interface CreateCommentResponse {
    id: number
    workId: number
    userId: number
    content: string
    parentId?: number | null
    replyToUserId?: number | null
    likesCount: number
    repliesCount: number
    createdAt: string
    user: {
        id: number
        username: string
        avatar?: string
    }
    replyToUser?: {
        id: number
        username: string
        avatar?: string
    }
}

// 评论列表响应
export interface CommentsListResponse {
    data: CommentInfo[]
    total: number
    page: number
    limit: number
    totalPages: number
}

/**
 * API 响应格式
 */
interface ApiResponse<T> {
    success: boolean
    statusCode: number
    message: string
    data: T
}

/**
 * 创建评论
 */
export async function createComment(data: CreateCommentRequest): Promise<CreateCommentResponse> {
    const response = await post<ApiResponse<CreateCommentResponse>>('/comments', data)
    return response.data
}

/**
 * 获取作品的评论列表（一级评论）
 */
export async function getWorkComments(
    workId: number,
    page: number = 1,
    limit: number = 20
): Promise<CommentsListResponse> {
    const response = await get<ApiResponse<CommentsListResponse>>(`/comments/work/${workId}`, {
        page,
        limit
    })
    return response.data
}

/**
 * 获取评论的回复列表（二级评论）
 */
export async function getCommentReplies(
    commentId: number,
    page: number = 1,
    limit: number = 10
): Promise<CommentsListResponse> {
    const response = await get<ApiResponse<CommentsListResponse>>(`/comments/${commentId}/replies`, {
        page,
        limit
    })
    return response.data
}

/**
 * 删除评论
 */
export async function deleteComment(commentId: number): Promise<void> {
    return del(`/comments/${commentId}`)
}

/**
 * 点赞评论
 */
export async function likeComment(commentId: number): Promise<void> {
    await post<ApiResponse<void>>(`/comments/${commentId}/like`)
}

/**
 * 取消点赞评论
 */
export async function unlikeComment(commentId: number): Promise<void> {
    await del<ApiResponse<void>>(`/comments/${commentId}/like`)
}

